package com.sduonline.isdapp.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.sduonline.isdapp.model.Article;
import com.sduonline.isdapp.test.config.DatabaseConfig;
import com.sduonline.isdapp.util.ResultSet2JavaBean;

public class ConnectionDB {

	public static Connection connection = null;

	static {
		try {
			// 加载MySql的驱动类
			System.out.println("initial driver...");
			Class.forName(DatabaseConfig.DB_DRIVER);
		} catch (ClassNotFoundException e) {
			System.out.println("找不到驱动程序类 ，加载驱动失败！");
			e.printStackTrace();
		}
	}

	/**
	 * 建立数据库连接
	 * 
	 * @return 数据库连接
	 */
	public Connection getConnection() {
		try {
			// 获取连接
			System.out.println("Connecting...");
			connection = DriverManager.getConnection(DatabaseConfig.DB_URL, DatabaseConfig.USERNAME,
					DatabaseConfig.PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

	public static void main(String[] args) {
		Connection conn = new ConnectionDB().getConnection();
		try {
			// String sql =
			// "insert into isd_article(writer,content) values('234','234234')";
			String sql = "select * from isd_article where id = ?";
			System.out.println("Prepare statement...");
			PreparedStatement ptmt = conn.prepareStatement(sql);
			ptmt.setInt(1, -1);
			ResultSet rs = ptmt.executeQuery();
			System.out.println("rs's column is " + rs.getMetaData().getColumnCount());
			while (rs.next()) {
				Article a = new Article();
				try {
					new ResultSet2JavaBean().setParameter2JavaBean(rs, a);
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println(a.getId());
				System.out.println(a.getBaseUrl());
				System.out.println(a.getCategory());
				System.out.println(a.getContent());
				System.out.println(a.getTitle());
				System.out.println(a.getTime());
				System.out.println(a.getWeb());
			}
			rs.close();
			ptmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
